package com.daoos.common.support.orm.db;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 配置多数据源
 *
 * @author daoos
 * @email daoos@daoos.com
 * @url www.daoos.com
 * @date 2017年9月3日 下午8:03:40
 */
@Configuration
@MapperScan(basePackages = {"com.daoos.modules.**.dao"}, sqlSessionTemplateRef = "mysqlSqlSessionTemplate")
public class DynamicDataSourceConfig {

    @Bean(name="masterDataSource")
    @Primary
    @ConfigurationProperties("spring.datasource.druid.masterDataSource")
    public DataSource defaultDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

//    @Bean
//    @Primary
//    public DynamicDataSource dataSource(DataSource defaultDataSource) {
//        Map<String, DataSource> targetDataSources = new HashMap<>(2);
//        targetDataSources.put(DataSourceEnum.MASTER.getName(), defaultDataSource);
//        return new DynamicDataSource(defaultDataSource, targetDataSources);
//    }




    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory( @Qualifier("masterDataSource")DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis.xml"));
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql/**/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "mysqlTransactionManager")
    @Primary
    public DataSourceTransactionManager mysqlTransactionManager(@Qualifier("masterDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "mysqlSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("mysqlSqlSessionFactory") SqlSessionFactory mysqlSqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(mysqlSqlSessionFactory);
    }
}
